package list;

import items.addItem;
import items.editItem;
import shopping.manager.R;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ViewDebug.CapturedViewProperty;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import date.base.DbHelper;

public class ListEdit extends ListActivity {
	private GestureDetector GestureDetector;
	private View.OnTouchListener GestureListener;
	
	public static final int ACTIVITY_EDIT=1;
	
	private DbHelper DbHelper;
	private Long ListRowId;
	private String TableName;
	private long ItemId;
	private int DeleteId;
	
	private static final int ID_COLUMN = 0;
	private static final int LIST_NAME = 1;
	private static final int LIST_TABLE_NAME = 2;
	private static final int TOTAL_ITEM_VALUE_COLUMN = 4;
	private static final int DONE_COLUMN = 5;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_edit);
		DbHelper = new DbHelper(this);
		DbHelper.open();
		getListName();
		fillData();
		registerForContextMenu(getListView());
	}
	

	private void fillData() {
		String tableName = TableName;
		Cursor list = DbHelper.getAllItems(tableName);
		startManagingCursor(list);
		
		ViewBinder binder=new ViewBinder() {
			
			
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				CheckBox done = (CheckBox) view.findViewById(R.id.CheckBox01);
				if (columnIndex == DONE_COLUMN)	{
					switch (cursor.getInt(columnIndex)) {
					case 0:
						done.setChecked(false);
						return true;
					case 1:
						done.setChecked(true);
						return true;
					}
				}
				
				
				return false;
			}
		};
		
		String[] from = new String[] {DbHelper.ITEM_NAME, DbHelper.ITEM_VALUE, DbHelper.ITEM_QUANTITY, DbHelper.ITEM_TOTAL_ITEM_VALUE, DbHelper.ITEM_DONE};
		int[] to = new int[] {R.id.NameTextView, R.id.ItemValueTextView, R.id.QuantityTextView, R.id.TotalItemValueTextView, R.id.CheckBox01 };
    	
    	SimpleCursorAdapter shoppingList = new SimpleCursorAdapter(this, R.layout.item_row, list, from, to);
    	shoppingList.setViewBinder(binder);
    	
    	setListAdapter(shoppingList);
    }


	//to get the name of the list
	private void getListName() {
		Bundle extras = getIntent().getExtras();
		ListRowId = extras.getLong(DbHelper.LIST_ROWID);
		Cursor c = DbHelper.getList(ListRowId);
		String tableName = c.getString(LIST_TABLE_NAME);
		TableName = tableName;
		String name = c.getString(LIST_NAME);
		TextView tv = (TextView) findViewById(R.id.textView1);
		tv.setText(name.toUpperCase());
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Cursor c = (Cursor) l.getAdapter().getItem(position);
		int done=c.getInt(DONE_COLUMN);
		if (done==0) {
			DbHelper.updateDone(TableName, id, true);
			c.requery(); 
		} else if (done==1) {
			DbHelper.updateDone(TableName, id, false);
			c.requery();
		}
		calculateTotal();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.list_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.addItem){
			addItem();
		}
		else if(item.getItemId() == R.id.deleteItems){
			deleteDialog();
		}
		else if(item.getItemId() == R.id.export){
			
		}
		else if(item.getItemId() == R.id.uncheckAll){
			uncheckAll();
		}
		return super.onOptionsItemSelected(item);
	}


	private void addItem() {
		Intent i = new Intent(this, addItem.class);
		i.putExtra(DbHelper.ITEM_TABLE_NAME, TableName);
		startActivity(i);
	}
	
	private void deleteDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setMessage("Are you sure you want to delete?");
		dialog.setCancelable(false);
		dialog.setPositiveButton("Yes", new OnClickListener() {
			
			
			public void onClick(DialogInterface dialog, int which) {
				removeAll();
				fillData();
			}
		});
		
		dialog.setNegativeButton("No", new OnClickListener() {
			
			
			public void onClick(DialogInterface dialog, int which) {
				
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = dialog.create();
		alertDialog.show();
		
	}

	private boolean removeAll() {
		DbHelper.clearList(TableName);
		fillData();
		return true;
	}
	
	
	private void uncheckAll() {
		Cursor c = DbHelper.getAllItems(TableName);
		c.moveToFirst();
		while(!(c.isAfterLast())){
			DbHelper.changeDone(TableName,c.getLong(ID_COLUMN), false);
			c.moveToNext();
		}
		TextView tv=(TextView) findViewById(R.id.MainTotalTextView);
		tv.setText("0.0");
		fillData();
	}


	private void calculateTotal() {
		Cursor allItems = DbHelper.getAllItems(TableName);
		double total=0;
		allItems.moveToFirst();
		for (allItems.move(-1); allItems.moveToNext(); allItems.isAfterLast()) {
			if (allItems.getInt(DONE_COLUMN)==1) {
				total+=allItems.getDouble(TOTAL_ITEM_VALUE_COLUMN);
			}
		}
		
		total = (double) (Math.round(total*100))/100;
 		
		TextView tv=(TextView) findViewById(R.id.MainTotalTextView);
		tv.setText(Double.toString(total));
	}
	
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.item_context_menu, menu);
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		ItemId = info.id;
		if(item.getItemId() == R.id.editItem){
			Intent i = new Intent(this,editItem.class);
			i.putExtra(DbHelper.ITEM_ROWID, info.id);
			i.putExtra(DbHelper.ITEM_TABLE_NAME, TableName);
			startActivityForResult(i, ACTIVITY_EDIT);
		}
		else if(item.getItemId() == R.id.deleteItem){
			deleteConfirm();
		}
		return super.onContextItemSelected(item);
	}


	private void deleteConfirm() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setMessage("Are you sure?");
		dialog.setCancelable(false);
		dialog.setPositiveButton("Yes", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Cursor c = (Cursor) getListView().getAdapter().getItem(which);
				
				//Toast.makeText(ListEdit.this, "Table name: " + TableName, Toast.LENGTH_SHORT).show();
				//Toast.makeText(ListEdit.this, "Item id: " + ItemId, Toast.LENGTH_SHORT).show();
				
				DbHelper.removeItem(TableName, ItemId);
				c.requery();
				fillData();
				
			}
		});
		dialog.setNegativeButton("No", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = dialog.create();
		alertDialog.show();
		
	}
	

}

